package rpc.init;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

//@Component
@ConfigurationProperties(prefix = "xiaobaibai.rpc.server")
public class RpcConfig implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        this.valiedPreper();
    }

    //服务名
    private String serverName;

    //注册中心IP
    private String registryCenterIp;

    //注册中心端口号
    private Integer registryCenterPort;

    //当前的端口
    private String port;

    public String getServerName() {
        this.valiedPreper();
        return serverName;
    }

    public String getRegistryCenterIp() {
        this.valiedPreper();
        return registryCenterIp;
    }
    public Integer getRegistryCenterPort() {
        this.valiedPreper();
        return registryCenterPort;
    }

    public void setServerName(String serverName) {
        this.serverName = serverName;
    }

    public void setRegistryCenterIp(String registryCenterIp) {
        this.registryCenterIp = registryCenterIp;
    }

    public void setRegistryCenterPort(Integer registryCenterPort) {
        this.registryCenterPort = registryCenterPort;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public Integer getPort() {
        this.valiedPreper();
        return Integer.parseInt(port);
    }

    public String getIp() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        assert address != null;
        return address.getHostAddress();
    }

    private void valiedPreper(){
        if(StringUtils.isBlank(serverName)){
            throw new RuntimeException("serverName is Null");
        }
        if(StringUtils.isBlank(registryCenterIp)){
            throw new RuntimeException("registryCenterIp is Null");
        }
        if(registryCenterPort==null){
            throw new RuntimeException("registryCenterPort is Null");
        }
        if(StringUtils.isBlank(port)){
            throw new RuntimeException("port is Null");
        }
    }

}
